# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


# 项目路径: baidu/pipelines.py
import pymysql

class MySQLPipeline(object):
    def open_spider(self, spider):
        self.connection = pymysql.connect(
            host='localhost',
            user='root',
            password='root',
            db='shuzhiku',  # 替换为你的数据库名
            charset='utf8mb4',
            cursorclass=pymysql.cursors.DictCursor
        )
        self.cursor = self.connection.cursor()

    def close_spider(self, spider):
        self.connection.close()

    def process_item(self, item, spider):
        insert_sql = """
            INSERT INTO baidubaike (title, intro, url)
            VALUES (%s, %s, %s)
        """
        self.cursor.execute(insert_sql, (item['title'], item['info'], item['url']))
        self.connection.commit()
        return item
